<template>
  <div class="cart-page">
    <div class="page-header">
      <h1>购物车</h1>
    </div>

    <div v-if="!cartItems.length" class="empty-cart">
      <i class="fas fa-shopping-cart"></i>
      <p>购物车是空的</p>
      <router-link to="/" class="continue-shopping">继续购物</router-link>
    </div>

    <div v-else class="cart-container">
      <div class="cart-items">
        <div class="cart-header">
          <div class="select-all">
            <input 
              type="checkbox" 
              :checked="isAllSelected" 
              @change="toggleSelectAll"
            >
            <span>全选</span>
          </div>
          <div class="cart-actions">
            <button 
              class="action-btn delete-selected" 
              @click="deleteSelected"
              :disabled="!hasSelectedItems"
            >
              删除选中商品
            </button>
            <button 
              class="action-btn clear-cart" 
              @click="clearCart"
              :disabled="!cartItems.length"
            >
              清空购物车
            </button>
          </div>
        </div>
         <!-- 循环展示购物车商品 -->
        <div v-for="item in cartItems" :key="item.id" class="cart-item">
          <div class="item-select"><!-- 商品选择框 -->
            <!-- 商品复选框 -->
            <input 
              type="checkbox" 
              v-model="item.selected"
              @change="updateSelectAll"
            >
          </div>
          <div class="item-image">
            <img :src="item.image" :alt="item.name">
          </div>
          <div class="item-details">
            <h3>{{ item.name }}</h3>
            <p class="item-price">¥{{ item.price }}</p>
            <div class="quantity-controls">
               <!-- 商品数量控制 -->
              <button @click="decreaseQuantity(item)" :disabled="item.quantity <= 1">
                <i class="fas fa-minus"></i>
              </button>
               <!-- 显示商品数量 -->
              <span>{{ item.quantity }}</span>
              <button @click="increaseQuantity(item)">
                <i class="fas fa-plus"></i>
              </button>
            </div>
          </div>
           <!-- 商品小计和删除按钮 -->
          <div class="item-total">
            <p>小计: ¥{{ (item.price * item.quantity).toFixed(2) }}</p>
            <button @click="removeItem(item)" class="remove-btn">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
      </div>
       <!-- 购物车摘要 -->
      <div class="cart-summary">
        <h2>订单摘要</h2>
        <div class="summary-row">
          <span>已选商品:</span>
          <span>{{ selectedItemsCount }} 件</span>
        </div>
        <div class="summary-row">
          <span>商品总数:</span>
          <span>{{ totalItems }} 件</span>
        </div>
        <div class="summary-row">
          <span>商品总价:</span>
          <span>¥{{ subtotal.toFixed(2) }}</span>
        </div>
        <div class="summary-row">
          <span>运费:</span>
          <span>¥{{ shipping.toFixed(2) }}</span>
        </div>
        <div class="summary-row total">
          <span>总计:</span>
          <span>¥{{ total.toFixed(2) }}</span>
        </div>
        <router-link 
          to="/checkout" 
          class="checkout-btn"
          :class="{ disabled: !hasSelectedItems }"
          :style="{ pointerEvents: hasSelectedItems ? 'auto' : 'none' }"
        >
          <i class="fas fa-shopping-bag"></i>
          去结算
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

export default {
  name: 'Cart',
  setup() {
    const router = useRouter()
    const cartItems = ref([])// 购物车商品列表
    const shipping = ref(0)

    const loadCart = () => {
      const savedCart = localStorage.getItem('cart')
      cartItems.value = savedCart ? JSON.parse(savedCart) : []
      // 确保每个商品都有 selected 属性
      cartItems.value.forEach(item => {
        if (item.selected === undefined) {
          item.selected = false
        }
      })
      updateShipping()
    }
  // 更新运费
    const updateShipping = () => {
      shipping.value = subtotal.value >= 199 ? 0 : 20
    }
     // 保存购物车数据
    const saveCart = () => {
      localStorage.setItem('cart', JSON.stringify(cartItems.value))
      window.dispatchEvent(new Event('storage'))
    }
    // 增加商品数量
    const increaseQuantity = (item) => {
      item.quantity++
      saveCart()
      updateShipping()
    }
    // 减少商品数量
    const decreaseQuantity = (item) => {
      if (item.quantity > 1) {
        item.quantity--
        saveCart()
        updateShipping()
      }
    }
    // 删除商品
    const removeItem = (item) => {
      const index = cartItems.value.findIndex(i => i.id === item.id)
      if (index > -1) {
        cartItems.value.splice(index, 1)
        saveCart()
        updateShipping()
      }
    }
    // 全选切换
    const toggleSelectAll = () => {
      const newValue = !isAllSelected.value
      cartItems.value.forEach(item => {
        item.selected = newValue
      })
      saveCart()
    }
    // 更新全选状态
    const updateSelectAll = () => {
      saveCart()
    }
     // 删除选中商品
    const deleteSelected = () => {
      if (confirm('确定要删除选中的商品吗？')) {
        cartItems.value = cartItems.value.filter(item => !item.selected)
        saveCart()
        updateShipping()
      }
    }
    // 清空购物车
    const clearCart = () => {
      if (confirm('确定要清空购物车吗？')) {
        cartItems.value = []
        saveCart()
        updateShipping()
      }
    }
    // 计算商品总价
    const subtotal = computed(() => {
      return cartItems.value.reduce((total, item) => {
        return total + (item.price * item.quantity)
      }, 0)
    })
    // 计算总计
    const total = computed(() => {
      return subtotal.value + shipping.value
    })
    // 计算商品总数
    const totalItems = computed(() => {
      return cartItems.value.reduce((total, item) => total + item.quantity, 0)
    })
     // 计算已选商品数量
    const selectedItemsCount = computed(() => {
      return cartItems.value.reduce((total, item) => {
        return total + (item.selected ? item.quantity : 0)
      }, 0)
    })
    // 是否有选中商品
    const isAllSelected = computed(() => {
      return cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
    })

    const hasSelectedItems = computed(() => {
      return cartItems.value.some(item => item.selected)
    })

    const checkout = () => {
      if (!localStorage.getItem('isLoggedIn')) {
        router.push('/login')
        return
      }
      // TODO: Implement checkout logic
      alert('感谢您的购买！')
      cartItems.value = []
      saveCart()
    }

    onMounted(() => {
      loadCart()
    })

    return {
      cartItems,
      shipping,
      subtotal,
      total,
      totalItems,
      selectedItemsCount,
      isAllSelected,
      hasSelectedItems,
      increaseQuantity,
      decreaseQuantity,
      removeItem,
      toggleSelectAll,
      updateSelectAll,
      deleteSelected,
      clearCart,
      checkout
    }
  }
}
</script>

<style scoped>
.cart-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  font-size: 2.5em;
  color: #B784B7;
  margin-bottom: 10px;
}

.empty-cart {
  text-align: center;
  padding: 50px 20px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
}

.empty-cart i {
  font-size: 64px;
  color: #D4B8D4;
  margin-bottom: 20px;
}

.empty-cart p {
  font-size: 1.2em;
  color: #666;
  margin-bottom: 20px;
}

.continue-shopping {
  display: inline-block;
  padding: 12px 30px;
  background: #B784B7;
  color: white;
  text-decoration: none;
  border-radius: 25px;
  transition: all 0.3s ease;
}

.continue-shopping:hover {
  background: #9B6B9B;
  transform: translateY(-2px);
}

.cart-container {
  display: grid;
  grid-template-columns: 1fr 350px;
  gap: 30px;
}

.cart-items {
  background: white;
  border-radius: 15px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #F8F1F8;
  margin-bottom: 20px;
}

.select-all {
  display: flex;
  align-items: center;
  gap: 10px;
}

.select-all input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.cart-actions {
  display: flex;
  gap: 15px;
}

.action-btn {
  padding: 8px 15px;
  border: none;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 0.9em;
}

.delete-selected {
  background: #ff4d4f;
  color: white;
}

.delete-selected:hover:not(:disabled) {
  background: #ff7875;
}

.clear-cart {
  background: #ffa940;
  color: white;
}

.clear-cart:hover:not(:disabled) {
  background: #ffc069;
}

.action-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.item-select {
  display: flex;
  align-items: center;
  padding-right: 15px;
}

.item-select input[type="checkbox"] {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.cart-item {
  display: grid;
  grid-template-columns: auto 120px 1fr auto;
  gap: 20px;
  padding: 20px;
  border-bottom: 1px solid #F8F1F8;
}

.cart-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 120px;
  height: 120px;
  overflow: hidden;
  border-radius: 10px;
  background-color: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: contain;
  transition: transform 0.3s ease;
}

.item-image:hover img {
  transform: scale(1.05);
}

.item-details {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.item-details h3 {
  margin: 0;
  color: #333;
  font-size: 1.2em;
}

.item-price {
  color: #B784B7;
  font-size: 1.1em;
  font-weight: bold;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.quantity-controls button {
  width: 30px;
  height: 30px;
  border: none;
  background: #F8F1F8;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s ease;
  color: #B784B7;
}

.quantity-controls button:hover:not(:disabled) {
  background: #E8D8E8;
}

.quantity-controls button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.quantity-controls span {
  min-width: 30px;
  text-align: center;
  color: #333;
}

.item-total {
  text-align: right;
}

.item-total p {
  color: #B784B7;
  font-weight: bold;
  margin-bottom: 10px;
}

.remove-btn {
  background: none;
  border: none;
  color: #B784B7;
  cursor: pointer;
  padding: 5px;
  transition: all 0.3s ease;
}

.remove-btn:hover {
  color: #9B6B9B;
  transform: scale(1.1);
}

.cart-summary {
  background: white;
  border-radius: 15px;
  box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
  padding: 20px;
  position: sticky;
  top: 100px;
}

.cart-summary h2 {
  margin: 0 0 20px 0;
  color: #B784B7;
  font-size: 1.5em;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  color: #666;
}

.summary-row.total {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 2px solid #F8F1F8;
  font-size: 1.2em;
  font-weight: bold;
  color: #B784B7;
}

.checkout-btn {
  width: 100%;
  padding: 15px;
  background: #B784B7;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 1.1em;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 10px;
  text-decoration: none;
}

.checkout-btn:hover {
  background: #9B6B9B;
  transform: translateY(-2px);
}

.checkout-btn.disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
}

.checkout-btn.disabled:hover {
  background: #ccc;
  transform: none;
}

@media (max-width: 900px) {
  .cart-container {
    grid-template-columns: 1fr;
  }

  .cart-summary {
    position: static;
  }
}

@media (max-width: 600px) {
  .cart-item {
    grid-template-columns: 1fr;
    text-align: center;
  }

  .item-image {
    margin: 0 auto;
  }

  .item-total {
    text-align: center;
  }

  .quantity-controls {
    justify-content: center;
    margin: 15px 0;
  }
}
</style>